package com.zxp.utils.winEnvUtils;

import java.io.IOException;
import java.util.Scanner;

/**
 * Utility class for managing Windows system environment variables.
 */
public class EnvUtils {

    public static void main(String[] args) {
        try {
//            // Example: Modify an existing variable named MY_VARIABLE
//            modifyOrAddSystemEnvironmentVariable("MY_VARIABLE", "new_value");
//
//            // Example: Add a new variable named NEW_VARIABLE
//            modifyOrAddSystemEnvironmentVariable("NEW_VARIABLE", "new_value");
//
//            // Example: Delete an existing variable named OLD_VARIABLE
//            deleteSystemEnvironmentVariable("MY_VARIABLE");
//
//            // Example: Query the value of an existing variable named EXISTING_VARIABLE
//            String value = querySystemEnvironmentVariable("NEW_VARIABLE");
//            System.out.println("Value of EXISTING_VARIABLE: " + value);
            // Example: Append a new entry to the Path variable
            appendToSystemPath("C:\\Program Files\\Java\\jdk1.8.0_281\\bin\\test");
            modifyOrAddSystemEnvironmentVariable("Jdkh", "B:\\project\\jdkMan\\target\\jdkMan-1.0-SNAPSHOT-jar-with-dependencies.jar");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * Modifies an existing Windows system environment variable or adds a new one if it doesn't exist.
     *
     * @param variableName  The name of the variable to be modified or added.
     * @param variableValue The new value for the variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void modifyOrAddSystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        if (querySystemEnvironmentVariable(variableName) == null) {
            // Variable doesn't exist, add it
            addSystemEnvironmentVariable(variableName, variableValue);
        } else {
            // Variable exists, modify it
            modifySystemEnvironmentVariable(variableName, variableValue);
        }
    }

    // ... (other methods remain unchanged)

    /**
     * Modifies an existing Windows system environment variable.
     *
     * @param variableName  The name of the variable to be modified.
     * @param variableValue The new value for the variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void modifySystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        // Build the reg command for modification
        String command = "reg add \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v "
                + variableName + " /d \"" + variableValue + "\" /f";

        // Execute the command
        executeCommand(command);
    }
    /**
     * Deletes an existing Windows system environment variable.
     *
     * @param variableName The name of the variable to be deleted.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void deleteSystemEnvironmentVariable(String variableName)
            throws IOException, InterruptedException {
        // Check if the variable exists before attempting deletion
        if (querySystemEnvironmentVariable(variableName) != null) {
            // Variable exists, proceed with deletion
            String command = "reg delete \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" "
                    + "/v " + variableName + " /f";
            executeCommand(command);
        } else {
            // Variable doesn't exist, throw an error
            throw new RuntimeException("Variable does not exist: " + variableName);
        }
    }

    /**
     * Queries the value of an existing Windows system environment variable.
     *
     * @param variableName The name of the variable to query.
     * @return The value of the variable, or null if the variable does not exist.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static String querySystemEnvironmentVariable(String variableName)
            throws IOException, InterruptedException {
        // Build the reg query command
        String command = "reg query \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" "
                + "/v " + variableName;
        // Execute the command and capture the output
        Process process = new ProcessBuilder("cmd", "/c", command).start();
        Scanner scanner = new Scanner(process.getInputStream());

        // Read the output to get the variable value
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (line.startsWith(variableName)) {
                String[] parts = line.split("\\s+");
                if (parts.length == 3) {
                    return parts[2];
                }
            }
        }

        return null; // Variable not found
    }

    /**
     * Adds a new Windows system environment variable.
     *
     * @param variableName  The name of the new variable.
     * @param variableValue The value for the new variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void addSystemEnvironmentVariable(String variableName, String variableValue)
            throws IOException, InterruptedException {
        // Build the reg command for addition
        String command = "reg add \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v "
                + variableName + " /d \"" + variableValue + "\" /f";

        // Execute the command
        executeCommand(command);
    }

    /**
     * Executes a command using ProcessBuilder.
     *
     * @param command The command to execute.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    private static void executeCommand(String command) throws IOException, InterruptedException {
        // Create a ProcessBuilder object
        ProcessBuilder processBuilder = new ProcessBuilder("cmd", "/c", command);

        // Start the process and wait for it to complete
        Process process = processBuilder.start();
        int exitCode = process.waitFor();

        // Check if the command was executed successfully
        if (exitCode != 0) {
            throw new RuntimeException("Command execution failed. Exit code: " + exitCode);
        }
    }

    /**
     * Appends a new entry to the Windows system variable Path.
     *
     * @param newPathEntry The new entry to be appended to the Path variable.
     * @throws IOException          If an I/O error occurs during command execution.
     * @throws InterruptedException If the command execution is interrupted.
     */
    public static void appendToSystemPath(String newPathEntry) throws IOException, InterruptedException {
        // Get the current Path variable value
        String currentPath = System.getenv("PATH");
        // Append the new entry to the current Path variable value
        String newPath = currentPath + ";" + newPathEntry;
        // Build the reg command for modification
        String command = "reg add \"HKLM\\System\\CurrentControlSet\\Control\\Session Manager\\Environment\" /v PATH /t REG_EXPAND_SZ /d \"" + newPath + "\" /f";
        // Execute the command
        executeCommand(command);
    }
}
